//
//  swifttest1App.swift
//  swifttest1
//
//  Created by kologe on 2024/9/5.
//

import SwiftUI
import NetAction

//扫描的终端
var terminal_list:KzMutableArray<Scan> = KzMutableArray<Scan>(array: [])

//文件下载的信息，一旦同意下载就直接添加到这里
var fileDownloadArr:KzMutableArray<FileTransMessage> = KzMutableArray(array: [])
// 文件上传的信息，一旦服务端同意下载，就直接添加到这里
var fileUploadArr:KzMutableArray<FileTransMessage> = KzMutableArray(array: [])

//存放暂停发送的文件的数据，用于恢复原来传输的功能
var fileListenPauseArr:KzMutableArray<FileTransMessage> = KzMutableArray(array: [])
var fileClientPauseArr:KzMutableArray<FileTransMessage> = KzMutableArray(array: [])

let kzListener = KzTcpListener(port:NetMessage.shared().tcpPort, sta: 0, dnpdlg:DealNetData() )


@main
struct swifttest1App: App {
    
    let udpListener = UDPListener(port:getUdpPort())
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear(){
//                    tcpServer.start()
                    udpListener.prepare(port: getUdpPort())
                    udpListener.start()
                    
                    kzListener.prepare(port:NetMessage.shared().tcpPort, sta: 0, dnpdlg:DealNetData())
                    kzListener.start()
                    setLanguage("zh-Hans")
                    
                    readPauseFiles()
                    //测试使用swiftnio 的网络代码功能
//                    DispatchQueue.global().async {
//                        print(NetMessage.shared().getIPAddress())
//                        let nLis = InoTCPListener(host: NetMessage.shared().getIPAddress(), port: 18888)
//                        nLis.run()
//                        nLis.shutdown()
//                    }
                    
                    
                    
                }
                .onDisappear(){
//                    tcpServer.close()
                    kzListener.close()
                    udpListener.close()
                    //客户端关闭所有的端口
                    TCPClientManager.shared.clientDic.forEach { (key: ConId, value: TCPClient) in
                        value.close()
                    }
                    TCPClientManager.shared.clientDic.removeAll()
                    kzListener.conDic.removeAll()
                    flushAllFileData()
                    getPauseData()
                    savePauseFiles()
                }
            
            
        }
    }
    
    func setLanguage(_ languageCode: String) {
        UserDefaults.standard.set([languageCode], forKey: "AppleLanguages")
        UserDefaults.standard.synchronize()
    }
    
    
    func getPauseData(){
        fileListenPauseArr.removeAllObjects()
        fileDownloadArr.forEach { item in
            if (item.state == DOWNLOADPAUSE || item.state == DOWNLOADING ){
                item.state = DOWNLOADPAUSE
                fileListenPauseArr.add(obj: item)
            }
        }
        fileClientPauseArr.removeAllObjects()
        fileUploadArr.forEach{ item in
            if (item.state == DOWNLOADPAUSE || item.state == DOWNLOADING ){
                item.state = DOWNLOADPAUSE
                fileClientPauseArr.add(obj: item)
            }
        }
        fileDownloadArr.removeAllObjects()
        fileUploadArr.removeAllObjects()
    }
    
    func savePauseFiles(){
        var dic = Dictionary<String, Array<FileTransMessage>>()
        dic["listen"] = fileListenPauseArr.array
        dic["client"] = fileClientPauseArr.array
        var encoded = Data()
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted // 设置格式化为易读形式
        if(fileListenPauseArr.array.count + fileClientPauseArr.array.count > 0 ){
            encoded = try! encoder.encode(dic)
        }else{
            encoded = Data()
        }
        let path = FileController.createTempFile(DirName: "TransPauseLog", fileName: "TransPauseLog.txt")
        FileController.overwriteToFile(fileUrl: URL(fileURLWithPath: path), data: encoded)
    }
    
    func readPauseFiles(){
        let path = FileController.createTempFile(DirName: "TransPauseLog", fileName: "TransPauseLog.txt")
        if let data = FileController.readFromFile(fileUrl: URL(string: path)!){
            if data.isEmpty{
                return
            }
            do{
                let dic =  try JSONDecoder().decode(Dictionary<String, Array<FileTransMessage>>.self, from: data)
                dic["listen"]?.forEach({ ftm in
                    fileDownloadArr.add(obj: ftm)
                    fileListenPauseArr.add(obj: ftm)
                })
                dic["client"]?.forEach({ ftm in
                    fileUploadArr.add(obj: ftm)
                    fileClientPauseArr.add(obj: ftm)
                })
                
            }catch{
                error_log("readPauseFiles failed")
            }
           
        }
    }
    
    func flushAllFileData(){
        FileWriteManager.shared.fileDic.forEach { (key: FileId, value: FileDataMsg) in
            value.writeToFile()
        }
    }
    

   
}
